package net.caixiaomi.info.helper;

import android.Manifest;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.logger.Timber;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AppHelper {

    private static int SCREEN_WIDTH = 0;
    private static int SCREEN_HEIGHT = 0;

    /**
     * WI-FI.
     */
    private static final int NETWORKTYPE_WIFI = 0;
    /**
     * 2G.
     */
    private static final int NETWORKTYPE_2G = 1;
    /**
     * 3G.
     */
    private static final int NETWORKTYPE_3G = 2;
    private static final int NETWORKTYPE_UNKNOWN = 3;

    private static ExecutorService mExecutor = Executors.newCachedThreadPool();

    public static boolean isM() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    public static boolean isLollipopOrHigher() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    public static void hideKeyboard(@NonNull View view) {
        hideKeyboard(view, view.getContext());
    }

    public static void hideKeyboard(@NonNull View view, @NonNull Context activity) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Nullable
    public static Fragment getFragmentByTag(@NonNull FragmentManager fragmentManager, @NonNull String tag) {
        return fragmentManager.findFragmentByTag(tag);
    }

    @Nullable
    public static Fragment getVisibleFragment(@NonNull FragmentManager manager) {
        List<Fragment> fragments = manager.getFragments();
        if (fragments != null && !fragments.isEmpty()) {
            for (Fragment fragment : fragments) {
                if (fragment != null && fragment.isVisible()) {
                    Timber.d(fragment.getClass().getSimpleName(), fragment.isVisible());
                    return fragment;
                }
            }
        }
        return null;
    }

    @Nullable
    public static String saveBitmap(Bitmap image) {
        try {
            File file = FileHelper.generateFile("fa_image_icon");
            if (file.exists()) {
                file.delete();
            }
            OutputStream fOut = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.PNG, 70, fOut);
            fOut.flush();
            fOut.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            return null;
        }
    }

    public static int getScreenWidth(Context c) {
        return c.getResources().getDisplayMetrics().widthPixels;
    }

    public static Uri getUri(Context context, int resourceId) {
        return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getResources()
                .getResourcePackageName(resourceId) + '/' + context.getResources()
                .getResourceTypeName(resourceId) + '/' + context.getResources()
                .getResourceEntryName(resourceId));
    }

    /**
     * 判断某个应用是否安装
     *
     * @param packageName
     * @return
     */
    public static boolean isApllicationInstalled(String packageName) {
        boolean bRet = false;
        try {
            PackageManager packageManager = CommonApp.getInstance().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                bRet = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bRet;
    }

    public static void copy2Clipboard(String text) {
        try {
            android.content.ClipboardManager cmb =
                    (android.content.ClipboardManager) CommonApp.getInstance().getSystemService(android.content.Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", text);
            cmb.setPrimaryClip(clip);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 验证手机号是否合法
     *
     * @param phone 要验证的手机号
     * @return
     */
    public static boolean checkPhoneAvailable(String phone) {
        if (!TextUtils.isEmpty(phone) && phone.replaceAll(" ", "").length() == 11) {
            return true;
        }
        return false;
    }


    public static boolean checkPwdAcailable(String password) {

        return password.length() >= 6 && password.length() <= 20;
    }


    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public static JSONObject getHeaderInfo(Context context) {
        // 获取当前手机的品牌和型号：
        String brand = Build.BRAND;
        brand = brand.replaceAll(" ", "_");

        String model = Build.MODEL;
        model = model.replaceAll(" ", "_");

        int sdkversion = Build.VERSION.SDK_INT;

        String appVersion = getAppVersion(context);

        String mac = getLocalMacAddress(context);

        String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        JSONObject headerInfo = new JSONObject();

        headerInfo.put("plat", "android");
        headerInfo.put("appv", appVersion);
        headerInfo.put("apiv", "1");
        headerInfo.put("appid", context.getPackageName());
        headerInfo.put("mac", mac);
        headerInfo.put("w", String.valueOf(getScreenWidth(context)));
        headerInfo.put("h", String.valueOf(getScreenHeight(context)));
        headerInfo.put("os", Build.VERSION.RELEASE);
        headerInfo.put("mid", model);
        headerInfo.put("brand", brand);
        headerInfo.put("net", getNetwrokTypeStr());
        headerInfo.put("channel", getChanel(context));
        headerInfo.put("version", appVersion);
        headerInfo.put("androidid", androidId);
        return headerInfo;
    }

    public static String getChanel(Context context) {
        try {
            ApplicationInfo appInfo = CommonApp.getInstance().getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            String chanel = appInfo.metaData.getString("CHANEL");
            return chanel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static final int getAppVersionCode(Context context) {

        int appVersion = 0;

        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVersion = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
        }

        return appVersion;
    }

    /**
     * 获取版本名
     */
    public static final String getAppVersion(Context context) {

        String appVersion = null;

        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVersion = info.versionName; // 版本名
        } catch (PackageManager.NameNotFoundException e) {
        }

        return appVersion;
    }

    /**
     * MAC地址
     *
     * @return
     */
    public static String getLocalMacAddress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String result = info.getMacAddress();
        return result == null ? "" : result;
    }

    /**
     * getScreenHeight
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {

        if (SCREEN_HEIGHT == 0) {
            WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display d = w.getDefaultDisplay();
            int rotation = d.getRotation();

            // 根据屏幕方向获取手机屏幕的真实高度
            if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
                SCREEN_HEIGHT = d.getHeight();
            } else {
                SCREEN_HEIGHT = d.getWidth();
            }

        }

        return SCREEN_HEIGHT;
    }

    /**
     * getIMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        String imei = "";
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            imei = mTelephonyMgr.getDeviceId();
        }

        return imei == null ? "" : imei;
    }

    /**
     * getIMSI
     *
     * @param context
     * @return
     */
    public static String getIMSI(Context context) {
        String imsi = "";
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            imsi = mTelephonyMgr.getSubscriberId();
        }
        return imsi == null ? "" : imsi;
    }


    public static void setIndicator(TabLayout tabLayout) {
        try {
            //拿到tabLayout的mTabStrip属性

            Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
            mTabStripField.setAccessible(true);
            LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
            int margin = (int) CommonApp.getInstance().getResources().getDimension(net.caixiaomi.info.R.dimen.padding_10);
            int tabMode = tabLayout.getTabMode();

            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                View tabView = mTabStrip.getChildAt(i);
                //拿到tabView的mTextView属性
                Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                mTextViewField.setAccessible(true);
                TextView mTextView = (TextView) mTextViewField.get(tabView);
                tabView.setPadding(0, 0, 0, 0);
                //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                int width = 0;
                width = mTextView.getWidth();
                if (width == 0) {
                    mTextView.measure(0, 0);
                    width = mTextView.getMeasuredWidth();
                }
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                params.width = width;
                if (tabMode == TabLayout.MODE_FIXED) {
                    int screenWidth = AppHelper.getScreenWidth(CommonApp.getInstance());
                    margin = ((screenWidth / tabLayout.getTabCount()) - width) / 2;
                }
                params.leftMargin = margin;
                params.rightMargin = margin;
                tabView.setLayoutParams(params);
                tabView.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static int getResourceId(String instenceName) {
        if (instenceName != null) {
            try {

                int id = CommonApp.getInstance().getResources().getIdentifier(instenceName, "id", CommonApp.getInstance().getPackageName());
                return id;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    /**
     * 判断网络类型
     *
     * @return
     */
    public static int getNetworkType() {

        int type = NETWORKTYPE_UNKNOWN;

        ConnectivityManager connectMgr = (ConnectivityManager) CommonApp.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectMgr.getActiveNetworkInfo();

        if (info == null) {
            return type;
        }

        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            type = NETWORKTYPE_WIFI;
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

            type = NETWORKTYPE_3G;

            int subType = info.getSubtype();

            switch (subType) {
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                case TelephonyManager.NETWORK_TYPE_HSPA:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    type = NETWORKTYPE_3G;
                    break;
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    type = NETWORKTYPE_2G;
                    break;
                default:
                    break;
            }

        }

        return type;
    }


    /**
     * 返回网络类型
     *
     * @return
     */
    public static String getNetwrokTypeStr() {

        String result = "UNKNOWN";

        int networkType = getNetworkType();

        switch (networkType) {
            case NETWORKTYPE_2G:
                result = "2G";
                break;
            case NETWORKTYPE_3G:
                result = "3G";
                break;
            case NETWORKTYPE_WIFI:
                result = "WIFI";
                break;
            default:
                break;
        }

        return result;
    }

    /**
     * 在后台线程中执行
     *
     * @param runnable
     */
    public static void asynExecute(Runnable runnable) {
        mExecutor.execute(runnable);
    }

    /**
     * 判断某个应用是否安装
     *
     * @param packageName
     * @return
     */
    public static boolean bApllicationInstalled(String packageName) {
        boolean bRet = false;
        try {
            PackageManager packageManager = CommonApp.getInstance().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                bRet = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bRet;
    }

    public static void sendStatistics(String id) {
        sendStatistics(id, null, null);
    }

    public static void sendStatistics(String id, @Nullable String[] keys, @Nullable String[] values) {
        Map<String, String> atrr = new HashMap<>();
        if (keys != null && keys.length > 0 && values != null && values.length > 0) {
            for (int index = 0; index < keys.length; index++) {
                atrr.put(keys[index], values[index]);
            }
        }
        StatService.onEvent(CommonApp.getInstance(), id, id, 1, atrr);
    }


    public final static String getFileProviderName(Context context){
        return context.getPackageName()+".fileprovider";
    }

}
